package cn.edu.lingnan.servlet;

import cn.edu.lingnan.pojo.Student;
import cn.edu.lingnan.service.StudentService;
import cn.edu.lingnan.service.StudentServiceMysqlImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String sid=req.getParameter("sid");
        String password=req.getParameter("password");
        System.out.println("[DEBUG]登录账号："+sid+" 密码："+password);
        StudentService service=new StudentServiceMysqlImpl();
        Student student=service.findStudentBySidAndPassword(sid,password);
        if(student!=null){
            System.out.println("登录成功");
            HttpSession session=req.getSession();
            session.setAttribute("sright",student.getSright());//储存用户权限
            session.setAttribute("sid",student.getSid());
            if(Integer.parseInt(student.getSright())==1){
                session.setAttribute("name","管理员");
                System.out.println("管理员");
            }else{
                session.setAttribute("name","游客");
                System.out.println("游客");
            }
            System.out.println(session);
            resp.sendRedirect("/main.jsp");
        }else{
            System.out.println("账号或密码错误");
            resp.sendRedirect("/error.html");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
